package cn.wolfcode.web.interceptor;

import cn.hutool.core.date.DateUtil;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UtilContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class CheckPermissionInterceptor implements HandlerInterceptor {
    @Autowired
    private INoticeService noticeService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws IOException {
        //获取到session中的用户
        Employee employee = (Employee) request.getSession().getAttribute("USER_IN_SESSION");
        //获取到用户中的admin
        if (employee.isAdmin()){
            return true;//是超级管理员就放行
        }
        //用户未读的公告信息
        request.getSession().setAttribute("notices",noticeService.selectByIdNotice(employee.getId()));


        //因为拦截器拦截的可能是静态资源,所以先判断下是否是处理请求的方法
        if (handler instanceof HandlerMethod){
            //是就强转下
            HandlerMethod method = (HandlerMethod) handler;
            //通过注解获取权限表达式
            RequiredPermission annotation = method.getMethodAnnotation(RequiredPermission.class);
            //如果方法上的注解权限表达式为空,就放行
            if (annotation == null){
                return true;
            }
            //在session中找下权限
            //List<String> expression = (List<String>)request.getSession().getAttribute("EXPRESSION_IN_SESSION");
            List<String> expression = UtilContext.getExpression();
            System.out.println(expression);
            //获取注解下的权限表达式
            String expression1 = annotation.expression();
            System.out.println(expression1);
            //如果用户所拥有的权限不包含注解下的权限的话
            if (!expression.contains(expression1)){
                //重定向到控制器,给用户显示没有权限的页面
                response.sendRedirect("redirect:/noexpression");
                return false;
            }
        }
        //如果是静态资源就放行
        return true;
    }

}
